<?php

//防止双重转义
if (get_magic_quotes_gpc()){
	function stripslashes_deep($value){
		$value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
		return $value;
	}
	
	$_POST 		= array_map('stripslashes_deep', $_POST);
	$_GET 		= array_map('stripslashes_deep', $_GET);
	$_COOKIE 	= array_map('stripslashes_deep', $_COOKIE);
}

/**
 +------------------------------------------------------------------------------
 *
 * 
 * 项目函数库通常位于项目的Common 目录下面，文件名为common.php，该文件会在执行过程
 * 中自动加载，并和项目编译统一缓存，如果使用了分组部署方式，目录下存在"分组名称
 * /function.php"文件，也会根据当前分组执行时对应进行自动加载，因此项目函数库所有函数也都可
 * 以无需手劢载入而直接使用。
 +------------------------------------------------------------------------------
 */


/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function real_ip()
{
	static $realip = NULL;

	if ($realip !== NULL)
	{
		return $realip;
	}

	if (isset($_SERVER))
	{
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
		{
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

			/* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
			foreach ($arr AS $ip)
			{
				$ip = trim($ip);

				if ($ip != 'unknown')
				{
					$realip = $ip;

					break;
				}
			}
		}
		elseif (isset($_SERVER['HTTP_CLIENT_IP']))
		{
			$realip = $_SERVER['HTTP_CLIENT_IP'];
		}
		else
		{
			if (isset($_SERVER['REMOTE_ADDR']))
			{
				$realip = $_SERVER['REMOTE_ADDR'];
			}
			else
			{
				$realip = '0.0.0.0';
			}
		}
	}
	else
	{
		if (getenv('HTTP_X_FORWARDED_FOR'))
		{
			$realip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_CLIENT_IP'))
		{
			$realip = getenv('HTTP_CLIENT_IP');
		}
		else
		{
			$realip = getenv('REMOTE_ADDR');
		}
	}

	preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
	$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

	return $realip;
}

/**
 * 格式化金额
 *
 * @param unknown_type $m
 * @return unknown
 */
function money($m){
	return number_format($m, 2, '.', '');
}

/**
 * 当前时间
 *
 * @param unknown_type $time
 * @return unknown
 */
function full_date($time = null){
	if(is_null($time)){
		return date('Y-m-d H:i:s');
	}
	return date('Y-m-d H:i:s',$time);
}

/**
 * 空日期
 * @param null $time
 * @return string
 */
function null_date(){
    return '0000-00-00 00:00:00';
}

function short_date($time = null){
	if(is_null($time)){
		return date('Y-m-d');
	}
	return date('Y-m-d',$time);
}

/**
 * 失败
 * 
 * @param string $message        	
 * @param unknown $data        	
 */
function json_error($message = '', $data = array()) {
	json_out ( 0, $message, $data );
}

/**
 * 成功
 * 
 * @param string $message        	
 * @param unknown $data        	
 */
function json_success($message = '', $data = array()) {
	json_out ( 1, $message, $data );
}

//输出json
function json_out($success,$message='',$data = array()){	
	exit(json_encode(
		array(
			'success'	=>$success,
			'message'	=>$message,
			'data'		=>$data
		)
	));
}

//判断管理员未登录则跳转到登录页
function admin_login_check(){
	
	import("@.ORG.Admin");
	$cAdmin = new Admin();
	    
	$admin = $cAdmin->logged_info();
	
	if(is_null($admin)){
		redirect('/index.php/Admin/Login/');
	}
}

//判断是否有权限,没有则终止
function admin_role($role){

	$session_roles = session('admin_role');
	
	if($session_roles != 'all'){
		//管理员权限
		$roles = explode(',',$session_roles); 
	
		if(!in_array($role, $roles)){
			header("Content-type: text/html; charset=utf-8"); 
			exit('没有权限');
		}
	}
}


//判断是否有权限
function has_role($role){

	$session_roles = session('admin_role');
	
	if($session_roles === 'all'){
		return true;
	}else{
		//管理员权限
		$roles = explode(',',$session_roles); 
	
		return in_array($role, $roles);
	}
}


//替换换行符
function replace_wrap($string){
	return preg_replace('/(\n+)/i', '', $string);
}


/**
 * 是否为手机号
 * @param string $str	验证的手机号
 * @return bool			是返回true,否返回false
 */
function is_mobile($mobile)
{
	if (preg_match("/^1[358][0-9]{9}$/",$mobile)){
		return true;
	}else{
		return false;
	}
}

/**
 * 
 * 生成验证码
 * @param unknown_type $length
 */
function verify_code($length = 6){
	
	$code = '';
	for ($i = 0;$i < $length;$i++){
		$code .= strval(rand(0,10));	
	}
	
	return $code;
}


//分割字符串
function mb_str_split($str,$len){
	
	$strLen = mb_strlen($str,'UTF-8');

	$splitStr = array();
	if($len >= $strLen){
		$splitStr[] = $str;
	}else{
		//开始位置
		$start = 0;
		//分成多少个
		$splitCount = ceil($strLen / $len);
		for ($i =0;$i < $splitCount;$i++){
			$start = $i * $len;
			$splitStr[] = mb_substr($str, $start,$len,'UTF-8');
		}
	}
	
	return $splitStr;
}

/**
 * 
 * 时间
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

/*
 * 获取蛋糕
 */
function goods_get_cake($goods){
	
	//惊喜小物的分类
	$surprise = C('GOODS_SURPRISE');
	
	$cake = array();
	foreach($goods as $i => $g){
		
		if($g['cate_id'] != $surprise){
			$cake[] = $g;
		}
	}
	return $cake;
	
}

/**
 * 
 * 获取惊喜小物
 * @param unknown_type $goods
 */
function goods_get_surprise($goods){
	
	//惊喜小物的分类
	$surprise = C('GOODS_SURPRISE');
	
	$sGoods = array();
	foreach($goods as $i => $g){
		
		if($g['cate_id'] == $surprise){
			$sGoods[] = $g;
		}
	}
	return $sGoods;

}

/**
 * 
 * 404
 */
function header_404(){
	header('HTTP/1.1 404 Not Found');
	header("status: 404 Not Found");
	exit;
}



/**
 *
 * 防止刷新过快
 */
function anti_refresh(){

	//监视页面,和页面最快刷新时间
	$watch_page = array(
		'index.php' 	=> 1	//首页
	);

	//访问当前页
	$req_page = basename($_SERVER["SCRIPT_NAME"]);

	//不属于监视页面
	if(!array_key_exists($req_page,$watch_page)){
		return false;
	}
;
	//获取session
	$anti_refresh = array();
	if(!session('?anti_refresh')) {
   		 session('anti_refresh',array());
 	}else{
 		$anti_refresh = session('anti_refresh');
 	}

	//设置是否访问速度过快
	$toofast = false;
	//当前时间
	$time = time();
	//判断是否有当前访问url
	if(array_key_exists($req_page,$anti_refresh)){
		//在session中
		$anti_page = $anti_refresh[$req_page];
		//当前时间减最后访问时间小于敢快访问速度时
		$timeSpan = $watch_page[$req_page] - ($time - $anti_page['last_visit']);
		if($timeSpan > 0){
			$url = $_SERVER["REQUEST_URI"];
			//时间范围内多次刷新
			$toofast = true;
		}
	}

	//不在session中
	$_SESSION['anti_refresh'][$req_page] = array(
		'last_visit' => $time
	);


	//访问时间过快
	if($toofast){
		exit('ur to fast');
	}
}

//获取seo关键词
function seo_keywords(){
	//获取关键词
	import('@.ORG.Keywords');
	$cKeywords = new Keywords();
	return $cKeywords->get_keywords();
}


/**
 * 变量是否存在
 * 
 * @param unknown $value        	
 * @param string $default        	
 * @return unknown string
 */
function isset_set($value, $default = null) {
	if (isset ( $value )) {
		return $value;
	} else {
		return $default;
	}
}

// 批量获取get参数
function get($params) {
	
	$g = new Get ();
	
	$get = array ();
	foreach ($params as $i => $p){

		$name 		= isset_set($p[0]);
		$func 		= isset_set($p[1],'');
		$default 	= isset_set($p[2],null);
		
		$get [$name] = $g->_get($name ,$func,$default);
	}
	
	return $get;
}

// 批量获取post参数
function post($params) {
	
	$pt = new Post ();

	$post = array ();
	foreach ($params as $i => $p){

		$name 		= isset_set($p[0]);
		$func 		= isset_set($p[1],'');
		$default 	= isset_set($p[2],null);

		$post [$name] = $pt->_post($name ,$func,$default);
	}
	
	return $post;
}


// get,post错误处理
function admin_id_get() {
	return admin_id ( 'get' );
}

function admin_id_post() {
	return admin_id ( 'post' );
}

// ajax错误处理
function admin_id_ajax() {
	return admin_id ( 'ajax' );
}

// 获取session中的admin_id
function admin_id($type = null){
	
	//管理员的id
	import("@.ORG.Admin");
	$cAdmin = new Admin();
	    
	//登录当前管理员
	$admin = $cAdmin->logged_info();
	
	$admin_id = 0;
	if(!is_null($admin)){
		$admin_id = $admin['admin_id'];
	}
   	
	if ($admin_id > 0) {
		return $admin_id;
	} else {
		if ($type == 'ajax') {
			json_error ( '登录状态超时，请重新登录!' );
		} else if ($type == 'get' || $type == 'post') {
			redirect('/index.php/Admin/Login',1,'登录状态超时，请重新登录!');
		}else{
			return $admin_id;
		}
	}
}

//导入文件编码转换
function gbk_to_utf8($str){
	return trim(mb_convert_encoding($str, "UTF-8", "GBK"));
}

/**
* 解析上传的csv文件,最多1001单
* @param mixed $file csv文件名
* @param mixed $field_list 对应的字段
*/
function parse_csv_file($file)
{
	$order_cost_list = array();
	
	$fp = fopen($file['tmp_name'],"r");
	
	$lines = array();
	
	$row = 0;
	while ($data = fgetcsv($fp,80000,',')){
		$row++;
		
		foreach($data as $i=>$d){
			$data[$i] = gbk_to_utf8($d);
		}

		$lines[] = $data;
	}
	fclose($handle);	

    return $lines;
}

/**
 * 
 * 导出csv
 * @param $data
 * @param $file_name
 */
function export_csv($data,$file_name){
	
	$t = ",";
	$n = "\n";

	//标题
	$title = array_shift($data); 

	$cont = implode(',',$title).$n;

	foreach ($data as $i => $d){
		
		$line = array();
		foreach ($d as $j => $m){
			$line[] = str_replace(',', '', $m);	
		}
		
		$cont .= implode(',', $line).$n;
	}
	
	//防止导出文件名乱码
	$ua = $_SERVER["HTTP_USER_AGENT"];
	$encoded_filename = urlencode($file_name);
	$encoded_filename = str_replace("+", "%20", $encoded_filename);

	header('Content-Type: application/octet-stream');

	if (preg_match("/MSIE/", $ua)) {
	    header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
	} else if (preg_match("/Firefox/", $ua)) {
	    header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_name . '"');
	} else {
	    header('Content-Disposition: attachment; filename="' . $file_name . '"');
	}
	 	
    exit(iconv('utf-8', 'gbk', $cont));
}

/**
 * csv避免科学计数法
 * @param unknown $num
 */
function csv_number_wrap($num){
	return '="'.$num.'"';
}

/**
 * 数组映射
 * @param $array
 * @param $fields
 * @return array
 */
function map_array($array,$fields){

    $map  = array();
    foreach($array as $a){
        $map[$a[$fields]] = $a;
    }

    return $map;
}

/**
 * 去换行符
 */
function remove_eol($str){
    return preg_replace('/\n/','',$str);
}

/**
 * 转xml格式
 */
function xml_parser($str){
    $xml_parser = xml_parser_create();
    if(!xml_parse($xml_parser,$str,true)){
        xml_parser_free($xml_parser);
        return false;
    }else {
        return (json_decode(json_encode(simplexml_load_string($str)),true));
    }
}

/**
 * 从url获取商品编号
 * @param $goods_url
 */
function item_id($goods_url){
    preg_match('/\d+/',$goods_url,$match);

    $item_id = 0;

    if(isset($match[0])){
        $item_id = $match[0];
    }

    return $item_id;
}

/**
 * 两日期天数间隔
 * @param $d1
 * @param $d2
 * @return float
 */
function day_span($d1,$d2){

    $time_span = abs(strtotime($d2) - strtotime($d1));

    return floor($time_span / 86400);
}


/**
 * 排名可读化
 * @param $rank
 * @return string
 */
function rank_to_read($rank){

    //宽屏是60个共15行，一般是36个，9行

    //一页共36个
    $page_size = 36;

    //一行几个
    $line_size = 4;

    $pos = '';
    if($rank > 0){

        //第几页
        $page = ceil($rank / $page_size);

        //余几个
        $page_mod    = $rank % $page_size;

        //第几行
        $line = ceil($page_mod / $line_size);

        //第几行
        $line_mod = $page_mod % $line_size;

        $col = $line_mod;
        if($line_mod == 0){
            $col = $line_size;
        }
        $pos = $page.'-'.$line.'-'.$col;
    }

    return $pos;
}

/**
 * 结束时间
 * @param $end_time
 * @return unknown
 */
function end_time_add($end_time){
    $time = strtotime($end_time) + 86400;
    return full_date($time);
}


/**
 * 获取数组的某一列
 *
 * @param array $array
 * @param string $col_name
 * @param string $type
 * @return mixed
 */
function get_array_cols($array,$col_name,$type = 'array'){

    $cols = array();
    if(empty($array) || !is_array($array)){
        if($type == 'array'){
            return $cols;
        }else if($type == 'string'){
            return '0';
        }
    }

    foreach ($array as $a) {
        if(isset($a[$col_name])){
            $cols[] = $a[$col_name];
        }
    }

    if($type == 'array'){
        return $cols;
    }else if($type == 'string'){
        return implode(',',$cols);
    }
}

?>